# coding:utf-8
from sqlalchemy import Column, String, Integer, DateTime

from database import dbconnect, session_maker, model_list, model_dict

_, _, DBase = dbconnect()


class Host(DBase):
    __tablename__ = 'cmdb_host'
    __table_args__ = {'extend_existing': True}
    id = Column(Integer, primary_key=True)
    innerip = Column(String(255))
    outerip = Column(String(255))
    project = Column(String(255))
    owner = Column(String(255))
    name = Column(String(255))
    deleted = Column(Integer)
    area = Column(String(255))
    cloud_vendor = Column(String(255))
    net_zone = Column(String(255))
    product = Column(String(255))
    env = Column(String(255))
    ins_id = Column(String(255))
    comment = Column(String(255))
    status = Column(String(255))
    os = Column(String(255))
    arch = Column(String(255))
    cpu = Column(String(255))
    mem = Column(String(255))
    sysdisk = Column(Integer)
    datadisk = Column(Integer)
    operator = Column(String(255))
    phone = Column(String(255))
    ssh_port = Column(Integer)
    ssh_user = Column(String(255))
    ssh_password = Column(String(255))
    # 公共字段
    create_time = Column(DateTime)
    update_time = Column(DateTime)

    # 查询所有
    def find_all(self):
        with session_maker() as session:
            result = session.query(Host).filter_by(deleted=0).all()
            return model_list(result)

    # 根据id查询
    def find_by_id(self, id):
        with session_maker() as session:
            row = session.query(Host).filter_by(id=id).first()
            return model_dict(row)

    # 执行原生sql
    def exec_sql(self, raw_sql):
        with session_maker() as session:
            res = session.execute(raw_sql)  # res是获取的对象
            # all_res_list = res.fetchall()  # all_res_list具体的结果 是列表
            print(res.rowcount)
            return res.rowcount


if __name__ == '__main__':
    a = Host()
    li = a.find_all()
    print(li)
